package cn.magictodo.weblog.common.domain.mapper;

import cn.magictodo.weblog.common.domain.dos.CategoryDO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import java.time.LocalDate;
import java.util.List;

/**
 * @author liu
 * #time 2023-11-21 19:50
 */
public interface CategoryMapper extends BaseMapper<CategoryDO> {

    /**
     * 根据名查询
     * @param categoryName
     * @return
     */
    default CategoryDO selectByName(String categoryName) {
        // 构建查询条件
        LambdaQueryWrapper<CategoryDO> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CategoryDO::getName, categoryName);

        // 执行查询
        return selectOne(wrapper);
    }


    default Page<CategoryDO> selectPageList(Long current, Long size, String categoryName, LocalDate startDate, LocalDate endDate)
    {
        Page<CategoryDO> categoryDOPage = new Page<>(current,size);

        LambdaQueryWrapper<CategoryDO> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.like(categoryName!= null,CategoryDO::getName, categoryName)
                .ge(startDate!=null,CategoryDO::getCreateTime,startDate)
               .le(endDate!=null,CategoryDO::getCreateTime,endDate);

        return selectPage(categoryDOPage, queryWrapper);
    }


    /**
     * 查询时指定数量
     * @param limit
     * @return
      */
    default List<CategoryDO> selectByLimit(Long limit) {
        return selectList(Wrappers.<CategoryDO>lambdaQuery()
                .orderByDesc(CategoryDO::getPublishArticlesTotal) // 根据已发布文章总数降序
                .last(String.format("LIMIT %d", limit))); // 查询指定数量
    }
}
